<template>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <a href="/">基础数据</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>网格人员管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索区域 -->

    <div style="border: 1px solid red; margin: 10px 10px; padding: 12px;">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="部门名称">
                <el-input v-model="searchForm.departmentName" placeholder="请输入部门名称" clearable />
            </el-form-item>
            <el-form-item label="姓名">
                <el-input v-model="searchForm.realName" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getData()">搜索</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 表格区域 -->
    <div style="border: 1px solid #ccc; margin: 10px 10px; padding: 12px;">
        <el-button type="success" @click="addDialogVisible = true">添加</el-button>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column type="index" label="1" width="80" />
            <el-table-column prop="id" label="编号" width="140" />
            <el-table-column prop="name" label="账号" width="120" />
            <el-table-column prop="realName" label="真实姓名" width="80" />
            <el-table-column prop="phone" label="手机号" width="120" />
            <el-table-column prop="card" label="身份证号" width="280" />
            <el-table-column prop="departmentName" label="所属部门" width="150" />
            <el-table-column prop="roleName" label="角色" width="120" />
            <el-table-column fixed="right" label="操作" min-width="140">
                <template v-slot="scope">
                    <el-button type="primary" size="small" @click="update(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[2, 3, 4, 5, 6]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="page.totalCount" />
    </div>
    <!-- 添加弹窗 -->

    <el-dialog v-model="addDialogVisible" title="添加网格人员" width="666">
        {{ ruleForm }}

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>


            <el-form-item label="部门" prop="departmentId">
                <el-cascader style="width: 600px;" v-model="ruleForm.departmentId" :options="trees" :props="props1"
                    @change="cascaderChanged" clearable />
            </el-form-item>
            <el-form-item label="账号" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="ruleForm.realName" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="ruleForm.phone" />
            </el-form-item>
            <el-form-item label="身份证" prop="card">
                <el-input v-model="ruleForm.card" placeholder="身份证后六位为密码" />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                <!-- <el-checkbox-group v-model="ruleForm.roleId">
                    <el-checkbox value="3" name="type">
                        网格长
                    </el-checkbox>
                    <el-checkbox value="4" name="type">
                        网格员
                    </el-checkbox>
                </el-checkbox-group> -->
                <el-radio v-model="ruleForm.roleId" :value="3">网格长</el-radio>
                <el-radio v-model="ruleForm.roleId" :value="4">网格员</el-radio>

            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>


    <!-- 编辑弹窗 -->

    <el-dialog v-model="updateDialogVisible" title="修改网格人员" width="666">

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>


            <el-form-item label="部门" prop="departmentId">
                <el-cascader style="width: 600px;" v-model="ruleForm.departmentId" :options="trees" :props="props1"
                    @change="cascaderChanged" clearable />
            </el-form-item>
            <el-form-item label="账号" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
                <el-input v-model="ruleForm.realName" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="ruleForm.phone" />
            </el-form-item>
            <el-form-item label="身份证" prop="card">
                <el-input v-model="ruleForm.card" placeholder="身份证后六位为密码" />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                <!-- <el-checkbox-group v-model="ruleForm.roleId">
                    <el-checkbox value="3" name="type">
                        网格长
                    </el-checkbox>
                    <el-checkbox value="4" name="type">
                        网格员
                    </el-checkbox>
                </el-checkbox-group> -->
                <el-radio v-model="ruleForm.roleId" :value="3">网格长</el-radio>
                <el-radio v-model="ruleForm.roleId" :value="4">网格员</el-radio>

            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>



</template>

<script lang="ts" setup>

import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { tr } from 'element-plus/es/locales.mjs';
import { onMounted, reactive, ref, watch } from 'vue';

const searchForm = reactive({
    departmentName: '',
    realName: ''
})

const page = reactive({
    PageIndex: 1,
    PageSize: 4,
    totalCount: 0,
    totalPage: 0
});

watch(page, () => {
    getData()
})
const tableData = ref([]) //表格数据源
//查询网格人员的列表
const getData = () => {
    axios.defaults.headers.common["Authorization"] = "Bearer " + window.localStorage.getItem("token");
    axios.get('http://localhost:5015/api/Account/GetGridPersonPage', {
        params: {
            DepartName: searchForm.departmentName,
            RealName: searchForm.realName,
            PageIndex: page.PageIndex,
            PageSize: page.PageSize
        }
    }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.items
            page.totalCount = res.data.totalCount
            page.totalPage = res.data.totalPage
        }
    })
}

//查询表格数据
const search = () => {
    axios.get('http://localhost:5111/api/Logical/GetLogicGrid', { params: searchForm })
}

//级联
const props1 = {
    checkStrictly: true,
    value: 'id',
    label: 'departName'
}

const trees = ref([]);
const getTree = () => {
    axios.get('http://localhost:5015/api/Department').then(res => {
        trees.value = res.data.data
    });
}

const cascaderChanged = (value: any) => {
    ruleForm.departmentId = value[value.length - 1]
}
//删除数据
const del = (row: any) => {
    ElMessageBox.confirm(
        '您确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {

            axios.put("https://localhost:7038/api/Account/DelGridPerson", row)
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        getData();
                    }
                })



        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}

//编辑弹窗
const update = (row: any) => {
    updateDialogVisible.value = true;

    ruleForm.id = row.id;
    ruleForm.name = row.name;
    ruleForm.realName = row.realName;
    ruleForm.pass = "";
    ruleForm.phone = row.phone;
    ruleForm.card = row.card;
    ruleForm.roleId = row.roleId;
    ruleForm.departmentId = row.departmentId

}
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            //https://localhost:7038/api/Account/UpdateGridPerson
            axios.put('https://localhost:7038/api/Account/UpdateGridPerson', ruleForm).then(res => {
                if (res.data.code == 200) {

                    ElMessage.success(res.data.msg);
                    getData();
                    updateDialogVisible.value = false;
                } else {

                    ElMessage.error(res.data.msg);
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}



//添加弹窗
//控制弹窗是否显示的变量
const addDialogVisible = ref(false)
const updateDialogVisible = ref(false)

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
    "id": 0,
    "name": "",
    "realName": "",
    "pass": "string",
    "phone": "",
    "card": "",
    "roleId": 3,
    "departmentId": 0
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 10, message: '账号长度为3-10位', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }
    ],
    realName: [
        { required: true, message: '姓名不能为空', trigger: 'blur' },
        { min: 3, max: 8, message: '姓名长度为3-8位', trigger: 'blur' },
    ],

    card: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { min: 18, max: 18, message: '身份证长度为18', trigger: 'blur' },
    ]
    , roleId: [
        {

            required: true,
            message: '请选择角色',
            trigger: 'change',
        },
    ], departmentId: [
        { required: true, message: '请选择部门', trigger: 'change' },

    ]

})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {

            axios.post('https://localhost:7038/api/Account/CreateGridPerson', ruleForm).then(res => {
                if (res.data.code == 200) {

                    ElMessage.success(res.data.msg);
                    getData();
                    addDialogVisible.value = false;
                } else {

                    ElMessage.error(res.data.msg);
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}




const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

//就绪钩子函数
onMounted(() => {
    getData()
    getTree()
})
</script>